from flask import Flask, jsonify
from flask_jwt_extended import JWTManager
from datetime import timedelta
from flask_cors import CORS
import exts
# 导入蓝图
from blueprints.exams import exams_blueprint
from blueprints.scores import scores_blueprint
from blueprints.basic import basic_blueprint
from blueprints.classes import classes_blueprint
from blueprints.stu_infochanges import info_changes_blueprint
from blueprints.questions import questions_blueprint
from blueprints.students import students_blueprint
from blueprints.knowledge_points import knowledge_points_blueprint
from blueprints.gongzhonghao import gongzhonghao_blueprint

app = Flask(__name__)
CORS(app)

# 配置jwt
app.config['JWT_SECRET_KEY'] = 'B3BjJbi3PuPJsWa9FBva856KkbCViHPMQ-wc0YN0nvk'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=15)  # 方便测试，设置为15天
app.config['JWT_REFRESH_TOKEN_EXPIRES'] = timedelta(days=15)
jwt = JWTManager(app)

# 绑定蓝图
app.register_blueprint(exams_blueprint, url_prefix='/web/exams')
app.register_blueprint(scores_blueprint, url_prefix='/web/scores')
app.register_blueprint(basic_blueprint, url_prefix='/web/basic')
app.register_blueprint(classes_blueprint, url_prefix='/web/classes')
app.register_blueprint(info_changes_blueprint, url_prefix='/web/info_changes')
app.register_blueprint(questions_blueprint, url_prefix='/web/questions')
app.register_blueprint(students_blueprint, url_prefix='/web/students')
app.register_blueprint(knowledge_points_blueprint, url_prefix='/web/knowledge_points')
app.register_blueprint(gongzhonghao_blueprint, url_prefix='/web/gongzhonghao')


@jwt.token_in_blocklist_loader
def check_if_token_in_blacklist(jwt_header, jwt_payload):
    jti = jwt_payload["jti"]
    conn = None
    try:
        conn = exts.get_db()  # 获取数据库连接
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM TokenBlackList WHERE jti = ?", (jti,))
        found = cursor.fetchone()
        return found is not None
    except Exception as e:
        return False
    finally:
        if conn:
            conn.close()


@jwt.expired_token_loader
def expired_token_callback(jwt_header, expired_token):
    token_type = expired_token['type']
    return jsonify({
        'code': 401,
        'status': 'error',
        'message': f'{token_type} 已过期'
    }), 401


@jwt.invalid_token_loader
def invalid_token_callback(error):
    return jsonify({
        'code': 422,
        'status': 'error',
        'message': '无效的 Token'
    }), 422


@jwt.unauthorized_loader
def missing_token_callback(error):
    return jsonify({
        'code': 401,
        'status': 'error',
        'message': '缺少 Token'
    }), 401


@jwt.revoked_token_loader
def revoked_token_callback(jwt_header, jwt_data):
    return jsonify({
        'code': 401,
        'status': 'error',
        'message': 'Token 已撤销'
    }), 401


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)
